﻿using System;
using System.Collections.Generic;
using UnityEngine;


class ExperienceManager : MonoBehaviour
{
    private int currentLevel;
    private int xpToNextLevel;
    private int currentXp;
    private int aimXP;

    private int widthOffset;
    private int heightOffset;

    void Start()
    {
        heightOffset = 25;
        widthOffset = 50;
        currentLevel = 0;
        currentXp = 1;
        xpToNextLevel = calcNextExpStep();
        EventManager<int, Vector3>.AddListener("xp gain", onXPGain);
        EventManager<int>.AddListener("level up", onLevelUp);
    }

    void Update()
    {
        if(currentXp < aimXP)
        {
            currentXp += 5;
        }
        if (currentXp >= xpToNextLevel)
        {
            EventManager<int>.Raise("level up", currentLevel + 1);
        }
    }

    private int calcNextExpStep()
    {
        return (int)(Mathf.Exp(0.35f * (currentLevel + 1)) + 300 * currentLevel + 1000 );
    }

    void OnGUI()
    {
        GUI.Box(new Rect(widthOffset, heightOffset, Screen.width - 2 * widthOffset, 25), new GUIContent(""));
        GUI.Box(new Rect(widthOffset + 5, heightOffset + 5, (Screen.width - (2 * (widthOffset + 5))) * calculateWidthFactor(), 15), new GUIContent(""));
    }

    private float calculateWidthFactor()
    {
        return ((float)currentXp / (float)xpToNextLevel);
    }

    private void onXPGain(int gain, Vector3 position)
    {
        aimXP += gain;
    }

    private void onLevelUp(int level)
    {
        aimXP -= xpToNextLevel;
        currentXp = 1;
        currentLevel = level;
        xpToNextLevel = calcNextExpStep();
    }
}
